import os
import shutil
import traceback

from fastapi import APIRouter
from starlette.requests import Request
from starlette.responses import FileResponse, RedirectResponse
from xbase_util.db.bean.ConfigBean import ConfigBean

from base.bean.beans import ApiQueryBean, ApiCommonBean
from base.util.api_util import ApiUtil

webRouter = APIRouter()


@webRouter.post("/execDataExtraction",description="通过api开始获取数据")
def execDataExtraction(request: Request, bean: ApiQueryBean):
    try:
        print(f"请求ID：{bean.requestCode},表达式:{bean.expression}")
        config = ConfigBean(id=bean.requestCode, splitNumber=bean.splitNumber, description="webapi", session_size=5000,
                            session_alive="30m", session_start_time=bean.startTime, session_end_time=bean.endTime,
                            session_expression=bean.expression, session_all_true=False, pcap_process=5,
                            pcap_thread_in_process=70, pcap_per_subsection=2000, label_all_true=False, label_duration=5,
                            label_is_output_unmatch=True, catalogue=bean.catalogue)
        request.app.state.threadManager.start_thread(ApiUtil.saveDataExtractionTask,
                                                     config,
                                                     bean.callBackUrl,
                                                     bean.requestCode,
                                                     request.app.state.base_config,

                                                     request.app.state.redisUtil,
                                                     request.app.state.geoUtil,
                                                     request.app.state.esdb)
        return ApiUtil.wrap_correct("ok")
    except Exception as e:
        print(str(e))
        traceback.print_exc()


@webRouter.get("/finished/", description="重定向到/finished")
def list_files1(request: Request):
    path = request.url.path
    if path.endswith("/"):
        path = path[:-1]
    return RedirectResponse(url=path)


@webRouter.get("/finished", description="获取新提取的数据的列表")
async def list_files(request: Request):
    base_path = request.app.state.base_config['backup_path']['newfile']
    if not os.path.exists(base_path):
        return ApiUtil.wrap_error("路径不存在，请检查配置文件:backup_path")
    try:
        files = os.listdir(base_path)
        return ApiUtil.wrap_correct({"files": files, "base_path": base_path}, msg="文件可直接访问")
    except Exception as e:
        return ApiUtil.wrap_correct(f"错误: {str(e)}")


@webRouter.post("/del", description="逻辑删除，其实就是把文件移动到backup_path.oldfile/")
async def del_file(bean: ApiCommonBean, request: Request):
    newfile = request.app.state.base_config['backup_path']['newfile']
    oldfile = request.app.state.base_config['backup_path']['oldfile']
    origin_path = f"{newfile}/{bean.filename}"
    dst_path = f"{oldfile}/{bean.filename}"
    if not os.path.exists(origin_path):
        return ApiUtil.wrap_error("文件不存在，标记删除失败")
    try:
        shutil.copy(origin_path, dst_path)
        return ApiUtil.wrap_correct("标记删除成功")
    except Exception as e:
        return ApiUtil.wrap_correct(f"错误: {str(e)}")


@webRouter.get("/finished/{filename}", description="下载文件")
async def download_file(request: Request, filename):
    file_path = f"{request.app.state.base_config['backup_path']['newfile']}/{filename}"
    if os.path.exists(file_path):
        return FileResponse(path=file_path, media_type='application/octet-stream', filename=filename)
    else:
        return ApiUtil.wrap_correct("文件不存在")
